package com.mbmed.doctor.commons.vo.exception;

import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.apache.log4j.Logger;

import com.mbmed.doctor.commons.utils.ModelVo;
import com.mbmed.doctor.commons.utils.StaticKeys;

@Provider
public class ExceptionMapperSupport implements ExceptionMapper<Exception> {

	private static Logger logger = Logger.getLogger(ExceptionMapperSupport.class);
	
	@Override
	public Response toResponse(Exception e) {
		/*if(e instanceof BaseException){
			detailMessage = e.getMessage();
		}else{
			//detailMessage = ReflectUtil.getFieldValue(e.getCause(), "detailMessage");
			detailMessage = e.getMessage();
		}*/
//		ex.printStackTrace();
		String detailMessage = getDetailMessage(e);
//		String detailMessage = e.getMessage();
//		if(detailMessage==null || detailMessage.equals("")){
//			detailMessage = e.toString();
//			if(detailMessage==null){
//				detailMessage = "未知异常！";
//			}
//		}
		ModelVo mo = new ModelVo(StaticKeys.OH_FALSE);
		mo.setResultMsg(detailMessage);
		logger.info(detailMessage, e);
		
		//return Response.ok(mo, MediaType.APPLICATION_JSON).status(200).build();
		
		if(e instanceof AdviceException){
			return Response.ok(detailMessage, MediaType.APPLICATION_JSON).status(200).build();
		}else{
			return Response.ok(mo, MediaType.APPLICATION_JSON).status(200).build();
		}
	}

	private String getDetailMessage(Exception e) {
		String detailMessage = null;
		if(e instanceof BaseException){
			detailMessage = e.getMessage();
		}
		else if(e instanceof NullPointerException){
			detailMessage = "空指针异常";
		}
		else if(e instanceof ArithmeticException){
			detailMessage = "算术异常";
		}
		else if(e instanceof ClassCastException){
			detailMessage = "类型强制转换异常";
		}
		else if(e instanceof NegativeArraySizeException){
			detailMessage = "数组负下标异常";
		}
		else if(e instanceof ArrayIndexOutOfBoundsException){
			detailMessage = "数组下标越界异常";
		}
		else if(e instanceof SecurityException){
			detailMessage = "违背安全原则异常";
		}
		else if(e instanceof EOFException){
			detailMessage = "文件已结束异常";
		}
		else if(e instanceof FileNotFoundException){
			detailMessage = "文件未找到异常";
		}
		else if(e instanceof NumberFormatException){
			detailMessage = "字符串转换为数字异常";
		}
		else if(e instanceof SQLException){
			detailMessage = "操作数据库异常";
		}
		else if(e instanceof IOException){
			detailMessage = "输入输出异常";
		}
		else if(e instanceof NoSuchMethodException){
			detailMessage = "方法未找到异常";
		}
		
		if(detailMessage==null){
			detailMessage = e.toString();
			if(detailMessage==null){
				detailMessage = "未知异常";
			}
		}
		return detailMessage;
	}

}
